<template>
  <div id="chartCont">
    <div class="section">
      <div class="select-group">
        <div class="items">
          <span class="items-text">时间范围</span>
          <el-date-picker
            v-model="query.timeValue"
            type="daterange"
            unlink-panels
            :clearable='isclear'
            value-format='yyyy-MM-dd'
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickOption">
          </el-date-picker>
        </div>
      </div>
      <div class="select-group topLine">
        <div class="items">
          <span class="items-text">所属公司</span>
          <el-select v-model="query.companyId" :disabled="disableCompany" @change="companyChange" clearable filterable placeholder="请选择">
            <el-option
              v-for="item in companyArr"
              :key="item.companyId"
              :label="item.companyName"
              :value="item.companyId">
            </el-option>
          </el-select>
        </div>
        <div class="items">
          <span class="items-text">批次名称</span>
          <el-select
            v-model="query.sysFolder"
            clearable
            @change="refreshCustom"
            filterable
            :disabled="query.companyId == ''"
            placeholder="请选择">
            <el-option
              v-for="item in customFolderList"
              :key="item.folderId"
              :label="item.folderName"
              :value="item.folderName">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="select-group">
        <div class="items">
          <span class="items-text">拨打客服</span>
          <el-select v-model="query.userId"
                     :disabled="query.companyId == ''"
                     clearable
                     :multiple-limit="5"
                     @change="refreshKeyword"
                     multiple
                     filterable
                     placeholder="请选择">
            <el-option
              v-for="item in customUserList"
              :key="item.userId"
              :label="item.name"
              :value="item.userId">
            </el-option>
          </el-select>
        </div>
        <div class="items">
          <span class="items-text">客服文件</span>
          <el-select v-model="query.userFolder"
                     clearable
                     filterable
                     @change="refreshKeywordNouser"
                     :disabled="query.companyId == '' || query.userId.length > 1 "
                     placeholder="请选择">
            <el-option
              v-for="item in folderList"
              :key="item.folderId"
              :label="item.folderName"
              :value="item.folderName">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="select-group">
        <div class="items">
          <span class="items-text">呼叫范围</span>
          <el-select v-model="query.callRange"
                     clearable
                     :disabled="query.companyId == ''"
                     filterable
                     placeholder="请选择">
            <el-option
              v-for="item in callClassList"
              :key="item.callClassId"
              :label="item.callClassName"
              :value="item.callClassId">
            </el-option>
          </el-select>
        </div>
      </div>
      <div class="select-group topLine">
        <div class="items">
          <span class="items-text">关键词</span>
          <el-select v-model="query.keyword"
                     clearable
                     :disabled="query.companyId == ''"
                     multiple
                     filterable
                     placeholder="请选择">
            <el-option
              v-for="(item,idx) in keywordList"
              :key="idx"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
        <el-button  @click="getFormChartData" :disabled="isOk" size="medium" type="success" class="el-icon-search">
          <span style="padding-left:5px;">查询</span>
        </el-button>
      </div>
    </div>
    <div class="chartSelect">
      <div class="select-group">
        <div class="items">
          <span class="items-text">数量</span>
          <el-select v-model="selectOption.y1"
                     filterable
                     @change="getChartData"
                     placeholder="请选择">
            <el-option
              v-for="(item,idx) in selectOptionList.y1"
              :key="idx"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
        <el-popover
          ref="popover4"
          placement="bottom"
          width="400"
          trigger="click">
          <el-table id="popTable" :data="gridData">
            <el-table-column width="100" property="date" label="类型">
              <template slot-scope="scope">
                <span>{{scope.row.text}}</span>
              </template>
            </el-table-column>
            <el-table-column width="200" property="name" label="说明">
              <template slot-scope="scope">
                <span>{{scope.row.label}}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-popover>
        <div class="items" style="float: right">
          <span class="items-text">比率 <i  v-popover:popover4 style="color:#5f5f5f;cursor: pointer" class="fa fa-question-circle-o"></i> </span>
          <el-select v-model="selectOption.y2"
                     filterable
                     @change="getChartData"
                     placeholder="请选择">
            <el-option
              v-for="(item,idx) in selectOptionList.y2"
              :key="idx"
              :label="item"
              :value="item">
            </el-option>
          </el-select>
        </div>
      </div>
    </div>
    <div class='chart-container'>
      <chart ref="chart" :reportData="reportData" height='100%' width='100%'></chart>
    </div>
    <div class="tableComp">
      <el-table empty-text="暂无任何数据信息" max-height="350" :data="tableData"  border fit style="width: 100%">
        <el-table-column align="center" label="客服" >
          <template slot-scope="scope">
            <span>{{scope.row.name}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="数据总数" >
          <template slot-scope="scope">
            <span>{{scope.row.allCount}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="分配数" >
          <template slot-scope="scope">
            <span>{{scope.row.allotCount}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="拨打数">
          <template slot-scope="scope">
            <span>{{scope.row.callCount}}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="接听数">
          <template slot-scope="scope">
            <span>{{ scope.row.answerCount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="未接听数">
          <template slot-scope="scope">
            <span>{{ scope.row.unAnswerCount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="意向数">
          <template slot-scope="scope">
            <span>{{ scope.row.tranCount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="意向率">
          <template slot-scope="scope">
            <span>{{(scope.row.tranRatio * 100).toFixed(2) + '%' }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="留电数">
          <template slot-scope="scope">
            <span>{{ scope.row.phoneCount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="留微数">
          <template slot-scope="scope">
            <span>{{ scope.row.weChatCount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="留项目数">
          <template slot-scope="scope">
            <span>{{ scope.row.itemCount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="留医院数">
          <template slot-scope="scope">
            <span>{{ scope.row.hospitalCount }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="男性数量">
          <template slot-scope="scope">
            <span>{{ scope.row.man }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="女性数量">
          <template slot-scope="scope">
            <span>{{ scope.row.female }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="男性标签准确率">
          <template slot-scope="scope">
            <span>{{ scope.row.markMan + ' / ' + scope.row.labelMan }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="女性标签准确率">
          <template slot-scope="scope">
            <span>{{ scope.row.markFemale + ' / ' + scope.row.labelFemale }}</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import Chart from '@/components/ChartComp'
  import {getCompany} from '@/api/dataStock'
  import {getFolder} from '@/api/allocation'
  import {getCustom ,getKeyword ,getReportForm ,getReportChart,getCustomFolder} from "@/api/chart"

  export default {
    name: "chartcomponent",
    data() {
      var that = this;
      return {
        firstComming:true,
        disableCompany:false,
        gridData:[
          {text:'意向数',label:'留电数+留微数，之后再去重'},
          {text:'接通率',label:'已接听数 / 拨打数'},
          {text:'意向率',label:'意向数 / 已接听数'},
          {text:'留电话率',label:'留电数 / 已接听数'},
          {text:'留微信率',label:'留微数 / 已接听数'},
          {text:'留项目率',label:'留项目数 / 已接听数'},
          {text:'留医院率',label:'留医院数 / 已接听数'},
          {text:'既留电也留微',label:'既留电也留微 / 已接听数'},
          {text:'只留电或留微',label:'只留电或留微 / 已接听数'},
          {text:'男',label:'男性数量 / 已接听数'},
          {text:'女',label:'女性数量 / 已接听数'},
        ],
        isOk:false,
        tableData:[],
        reportData:null,
        query: {
          timeValue: '',
          companyId: '',
          userId: [],
          sysFolder: '',
          keyword: [],
          userFolder: '',
          callRange:''
        },
        selectOption:{
          y1:'拨打数',
          y2:'接通率'
        },
        selectOptionList:{
          y1:[
            "拨打数","接听数","未接听数","意向总数","留电话数","留微信数","留医院数","留项目数","男","女"
          ],
          y2:[
            "接通率","意向率","留电话率","留微信率","留项目率","留医院率","既留电也留微","只留电或留微","男","女"
          ]
        },
        isclear: false,
        companyArr: [],
        folderList: [],
        customUserList: [],
        customFolderList: [],
        keywordList: [],
        callClassList: [
          {"callClassId": 1, "callClassName": "全部数据"},
          {"callClassId": 2, "callClassName": "首拨数据"},
          {"callClassId": 3, "callClassName": "复拨数据"},
        ],
        pickOption: {
          disabledDate(time) {
            var minDate = new Date('2018-01-01');
            //日期最大为前一个月
            return minDate.getTime() > time.getTime() ||  time.getTime() > Date.now() - 8.64e6
          },
          shortcuts: [{
            text: '最近一周',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
              picker.$emit('pick', [start, end]);
            }
          }]
        },

      }
    },
    components: {
      Chart
    },
    computed:{
      ...mapGetters([
        'userInfo'
      ])
    },
    watch:{
      'query.timeValue'(val,oldVal){

        let startDate = new Date(val[0]).getTime();
        let endDate = new Date(val[1]).getTime();
        if(( endDate - startDate ) > 3600 * 24 * 30 * 1000 ){
          this.$message.warning('您选择的日期范围不能超过30天，请重新选择');
          this.query.timeValue = [];
          return;
        }

        if(!this.firstComming){
          if(JSON.stringify(oldVal) != JSON.stringify(val) ){
            this.clearData();
            this.fetchFormatData();
          }
        }else {
          this.firstComming = false;
        }


      }
    },
    mounted() {
      this.query.timeValue = [   //默认为前一周的时间
        this.getNowFormatDate(new Date(new Date().getTime() - 3600 * 1000 * 24 * 7)),
        this.getNowFormatDate(new Date())
      ]


      if(this.userInfo.roleId == 2 || this.userInfo.roleId == 1){
        this.getformatData()
      }else {
        this.companyArr = [{companyId:this.userInfo.companyId,companyName:this.userInfo.companyName}];
        this.query.companyId = this.userInfo.companyId;
        this.disableCompany = true;
        this.companyChange();
      };

    },
    methods: {
      getNowFormatDate(date) {
         var seperator1 = "-";
         var year = date.getFullYear();
         var month = date.getMonth() + 1;
         var strDate = date.getDate();
         if (month >= 1 && month <= 9) {
           month = "0" + month;
         }
         if (strDate >= 0 && strDate <= 9) {
           strDate = "0" + strDate;
         }
         var currentdate = year + seperator1 + month + seperator1 + strDate;
         return currentdate;
      },
      getformatData() { //获取公司列表
        return new Promise((resolve,reject) => {
          getCompany().then(res => {
            let temp = res.data.info;
            this.companyArr = temp;
            resolve();

          }).catch(res => {
            this.$message.error(res)
            reject();
          })
        })
      },
      getUserFolder(){   //获取客服文件
        if( this.query.userId.length > 1 ) return
        if(!this.query.timeValue.length){
          this.$message.warning('请先选择一个小于30日的日期范围')
          return
        }
        let tempData = {
          userId:this.query.userId[0],
          start:this.query.timeValue[0],
          end:this.query.timeValue[1]
        }
        getCustomFolder(tempData).then(res=>{
          this.folderList = res.data.info;
        }).catch(res=>{
          this.$message.error(res)
        })
      },
      getFolderData(){  //获取批次列表
        if(this.query.companyId == ''){
          this.$message.warning('请先选择一个公司')
          return
        }
        if(!this.query.timeValue.length){
          this.$message.warning('请先选择一个小于30日的日期范围')
          return
        }
        return new Promise((resolve,reject)=>{
          let tempData = {
            companyId:this.query.companyId,
            start:this.query.timeValue[0],
            end:this.query.timeValue[1]
          }
          getFolder(tempData).then(res => {
            this.customFolderList = res.data.info;
            resolve();
          }).catch(res => {
            this.$message.error(res)
            reject();
          })
        })
      },
      getCustomData(){  //获取客服列表
        if(this.query.companyId == ''){
          this.$message.warning('请先选择一个公司')
          return
        }
        let tempData = {companyId:this.query.companyId};
        if(this.query.sysFolder != ''){
           tempData['folder'] = this.query.sysFolder
        }
        getCustom(tempData).then(res => {
          this.customUserList = res.data.user;
        }).catch(res => {
          this.$message.error(res)
        })
      },
      getKeywordData(){ //获取关键词列表
        if(this.query.companyId == ''){
          this.$message.warning('请先选择一个公司')
          return
        }
        if(!this.query.timeValue.length){
          this.$message.warning('请先选择一个小于30日的日期范围')
          return
        }
        let tempData = {
          companyId:this.query.companyId,
          start:this.query.timeValue[0],
          end:this.query.timeValue[1]
        };
        this.query.sysFolder != '' ? tempData['sysFolder'] = this.query.sysFolder : '';
        this.query.userId != '' ? tempData['userId'] = this.query.userId : '';
        this.query.userFolder != '' ? tempData['userFolder'] = this.query.userFolder : '';
        getKeyword(tempData).then(res => {
          this.keywordList = res.data.keyword;
        }).catch(res => {
          this.$message.error(res)
        })
      },
      companyChange(val){
        this.clearData()
        this.query.companyId == '' ? null  : this.fetchFormatData();
      },
      fetchFormatData(){
        //先请求公司再请求客服
        this.getFolderData().then(res=>{
          this.getCustomData();
          this.getKeywordData();
        }).catch(res=>{
          this.$message.error(res);
        });
      },
      clearData(){
        this.query.sysFolder = ''; //清空批次名称
        this.query.userId = []; //清空客服
        this.query.userFolder = ''; //清空客服文件
        this.query.keyword = []; //清空关键词

        this.customFolderList = []; //清空批次列表
        this.customUserList = []; //清空客服列表
        this.folderList = []; //清空客服文件列表
        this.keywordList = []; //清空关键词列表
      },
      refreshCustom(){    //点击批次名称 会触发的事件
        this.query.userId = [];
        this.query.keyword = [];
        this.getCustomData();
        this.getKeywordData();
      },
      refreshKeyword(){
        this.query.keyword = [];
        this.query.userFolder = '';
        this.getKeywordData();
        this.getUserFolder();
      },
      refreshKeywordNouser(){    //点击客服下拉 会触发的事件
        this.query.keyword = [];
        this.getKeywordData();
        this.getUserFolder();
      },
      getSeachData(flag){
        let temp = Object.assign({},this.query,flag ? this.selectOption : {});
        for(var k in temp){
          if(k == 'timeValue'){
            temp['startTime'] = temp[k][0];
            temp['endTime'] = temp[k][1];
            delete temp[k];
          }

          if(!temp[k] || temp[k] == ''){
            delete temp[k]
          }
        }
        return temp
      },
      getFormChartData(){
        let tempChartData = this.getSeachData();

        getReportForm(tempChartData).then(res=>{
          this.tableData = res.data.report;
        }).catch(res=>{
          this.$message.error(res)
        })

        this.getChartData();
      },
      getChartData(){
        this.isOk = true;
        let tempFormData = this.getSeachData(true);
        this.$refs['chart'].chart.showLoading();
        getReportChart(tempFormData).then(res=>{
          this.isOk = false;
          this.reportData = res.data;
          this.$refs['chart'].chart.hideLoading()
        }).catch(res=>{
          this.isOk = false;
          this.$message.error(res)
          this.$refs['chart'].chart.hideLoading()
        })
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>
  #chartCont {
    .section {
      display: inline-block;
      .select-group {
        &.topLine {
          padding-top: 15px;
          border-top: 1px solid #ccc;
        }
        margin-left: 100px;
        margin-bottom: 15px;
        .items-text {
          display: inline-block;
          width: 95px;
          text-align: right;
          margin-right: 20px;
        }
        .items {
          min-width: 400px;
          display: inline-block;
        }
      }
    }
    .chartSelect {
      margin-top: 20px;
      .select-group {
        .items-text {
          display: inline-block;
          width: 95px;
          text-align: right;
          margin-right: 20px;
        }
        .items {
          min-width: 400px;
          display: inline-block;
        }
      }
    }
    .chart-container {
      position: relative;
      width: 100%;
      height: 500px;
      display: inline-block;
      padding: 40px 0;
    }
  }
</style>
